package com.lagou.rabbit.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lagou.rabbit.demo.enums.OrderStatus;
import com.lagou.rabbit.demo.mapper.OrderMapper;
import com.lagou.rabbit.demo.po.Order;
import com.lagou.rabbit.demo.service.OrderService;
import com.lagou.rabbit.demo.utils.IdUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public boolean saveOrder(Order order) {

        order.setId(IdUtil.genOrderId());
        order.setOrderNo(IdUtil.genOrderNo());
        Date date = new Date();
        order.setCreateTime(date);
        order.setUpdateTime(date);
        order.setStatus(OrderStatus.CREATE.getCode());

        final int inserted = orderMapper.insert(order);
        boolean flag = inserted == 1;

        rabbitTemplate.send("e.ttl", "r.ttl", new Message(order.getOrderNo().getBytes(), MessagePropertiesBuilder.newInstance().build()));

        return flag;
    }

    @Override
    @Transactional
    public boolean cancelOrder(Order order) {

        final Order orderDB = orderMapper.selectOne(new QueryWrapper<Order>()
                .eq("order_no", order.getOrderNo())
        );

        if (orderDB == null || orderDB.getStatus() != OrderStatus.CREATE.getCode()) {
            System.err.println("无需更新");
            return false;
        }

        final int updated = orderMapper.update(null, new UpdateWrapper<Order>()
                .set("status", OrderStatus.CANCEL.getCode())
                .set("update_time", new Date())
                .eq("order_no", order.getOrderNo())
        );

        return updated == 1;
    }

    @Override
    @Transactional
    public boolean payOrder(Order order) {
        final int updated = orderMapper.update(null, new UpdateWrapper<Order>()
                .set("status", OrderStatus.PAYED.getCode())
                .eq("order_no", order.getOrderNo())
        );
        return updated == 1;
    }

    @Override
    public List<Order> listOrders(Integer userId) {
        return orderMapper.selectList(new QueryWrapper<Order>().eq("user_id", userId));
    }
}
